package com.emip.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.emip.bean.SiteItemBean;
import com.emip.config.CommonOperation;
import com.emip.dao.BaseDAO;
import com.emip.dao.SiteItemDAO;


@Repository("siteItemDAO")
public class SiteItemDAOImpl extends BaseDAO implements SiteItemDAO {

	public int add(SiteItemBean entity) {
		Integer id = (Integer) this.getHibernateTemplate().save(entity);
		return id.intValue();
	}

	public SiteItemBean findByID(int id) {
		return getHibernateTemplate().get(SiteItemBean.class, id);
	}

	public void remove(SiteItemBean entity) {
		getHibernateTemplate().delete(entity);
	}

	public void update(SiteItemBean entity) {
		getHibernateTemplate().update(entity);
	}

	@SuppressWarnings("unchecked")
	public List<SiteItemBean> getAll() {
		return getHibernateTemplate().find("from SiteItemBean m order by m.id");
	}

	public Boolean findExist(SiteItemBean entity) {
		//Object[] params = new Object[] {entity.getSite().getId(), entity.getItem().getId()};
		Object[] params = new Object[] {entity.getSite(), entity.getItem()};
		List<SiteItemBean> result = this.getHibernateTemplate().find("from SiteItemBean m where site=? and item=?", params);
		if (result.size()==0) {
			return false;
		}
		else {
			//是否存在的那条记录的alarmID 和 alarmName 和自己是相同的，如果是的话，那么其实是update其他字段的一种操作，也是合法操作
			if (entity.getId()==0) {  //新增的情况
				return true;
			} else {
				SiteItemBean eBean = this.getHibernateTemplate().get(SiteItemBean.class, entity.getId());
				if (entity.getSite().equals(eBean.getSite()) &&
						entity.getItem().equals(eBean.getItem())) {
					return false;
				} else {
					return true;
				}
			}
		}
	}	
	
	public List<SiteItemBean> getItemSitesBySiteID(String siteID) {
		List<SiteItemBean> beans = this.getHibernateTemplate().find("from SiteItemBean m where siteID=? order by m.id", siteID);
		return beans;
	}

	public SiteItemBean findSiteItem(String siteID, String itemID) {
		List<SiteItemBean> beans = this.getHibernateTemplate().find("from SiteItemBean m where siteID=? and itemID=? order by m.id", siteID, itemID);
		if (beans != null && beans.size() > 0) {
			return beans.get(0);
		}
		return null;
	}

	public int addAllItems(String siteID) {
		String sql = "insert into t_siteitem a (id, siteid, itemid, emaxvalue, eminvalue, overmaxvalue, overminvalue, standunit, scale, maxrange, minrange, factor, alarmid)"
			+ " select s_Siteitem_Id.Nextval,'"+siteID+"', b.id, b.emaxvalue,b.eminvalue,b.overmaxvalue,b.overminvalue,b.standunit,b.scale,b.maxrange,b.minrange,1,"
			+ " (select min(c.id) from t_alarmconfig c)"
			+ " from t_item b"
			+ " where b.id not in (select d.itemid from t_siteitem d where d.siteid='"+siteID+"')";
		System.out.println(">>>>>HQL:"+sql);
		return CommonOperation.getInstance().executeUpdateSQL(this.getHibernateTemplate().getSessionFactory().openSession().connection(), sql);
	}

}
